package cn.it.hbtt.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONWriter;
import com.mysql.cj.xdevapi.JsonArray;

import cn.it.hbtt.dao.BaseDAO;
import cn.it.hbtt.entity.User;

import javax.servlet.http.HttpSession;
/**
 * Servlet implementation class CartAddProductServlet
 */
@WebServlet(name = "cartAddProductServlet", urlPatterns = { "/cartAddProductServlet" })
  public class CartAddProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServle    tResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
       boolean  result=true;
      // String resultStr=JSON.toJSONString(result);
       String resultStr=new String("{\"result\":\"true\"");
       //如果添加商品到购物车成功
       JSONObject object = new JSONObject();
	    object.put("addresult", "true");
 
       PrintWriter out=response.getWriter();
       out.println(object);
       out.flush();
       out.close();
       
       String showid=request.getParameter("productId");
		System.out.println(showid);
       if (showid==null) {
    	   String  str="<script  type='text/javascript'>";
			str+="alert('添加失败');";
			str+="location.href='http://localhost:8080/easybuy/Product.jsp'";
			str+="</script>";
			out.write(str);
			out.flush();
	}
       
       User user = (User)request.getSession().getAttribute("q");
       int id=user.getId();
       System.out.println(id);
       try {
    	   BaseDAO base = new BaseDAO();
			Connection conn = base.getConnection();
			System.out.println(conn);

			Statement stm = conn.createStatement();
			ResultSet rs = stm.executeQuery("select * from easybuy_buycar");
    	   
    	   
			
			
			System.out.println(conn);
			String sql = "insert into easybuy_buycar (showId,number,id,gross) values(?,?,?,?)";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, showid);
			// 为sql语句中的问号赋值
			ps.setString(2, "1");
			ps.setInt(3, id);
			ps.setString(4, "123");
			// 执行sql语句
            ps.executeUpdate();
            // 关闭数据库连接对象
			conn.close();
		
    	   
		
	} catch (Exception e) {
		// TODO: handle exception
	}
       
		
		
		
       
	}

}
